package com.zbkj.common.config;

import com.zbkj.common.utils.mqtt.ConnectionOptionWrapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * MQTT配置
 */
@Configuration
@Slf4j
public class AliMqttConfig {

    @Value("${aliyun.mqtt.accessKeyId}")
    public String accessKeyId;

    @Value("${aliyun.mqtt.accessKeySecret}")
    public String accessKeySecret;

    @Value("${aliyun.mqtt.instanceId}")
    public String instanceId;

    @Value("${aliyun.mqtt.regionId}")
    public String regionId;

    @Value("${aliyun.mqtt.serverUrl}")
    public String serverUrl;

    @Value("${aliyun.mqtt.clientId1:GID_bm47@@@bm47-0007}")
    public String clientId1;

    @Value("${aliyun.mqtt.clientId2:GID_bm47@@@bm47-0008}")
    public String clientId2;

    @Value("${aliyun.mqtt.clientId3:GID_bm47@@@bm47-0009}")
    public String clientId3;

    @Value("${aliyun.mqtt.clientId6:GID_bm47@@@bm47-0025}")
    public String clientId6 = "GID_bm47@@@bm47-0025";

    @Value("${aliyun.mqtt.topic:topic_bm47_test1}")
    public String parentTopic;

    public ConnectionOptionWrapper connectionOptionWrapper;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MemoryPersistence memoryPersistence = new MemoryPersistence();
        MqttClient client = new MqttClient("tcp://" + serverUrl, clientId2, memoryPersistence);
        client.setTimeToWait(5000);
        return client;
    }

    @PostConstruct
    public void initConfig() throws MqttException {
        try {
            log.info("初始化MQTT配置 clientId2：{} / {}", clientId2, parentTopic);
            connectionOptionWrapper = new ConnectionOptionWrapper(instanceId, accessKeyId, accessKeySecret, clientId2);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
}